package com.example.week9homework;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;


import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.TextView;

import java.text.SimpleDateFormat;
import java.util.Date;

public class Cast extends AppCompatActivity {

    TextView msgPanel;  //页面消息标签
    MinuteBroadcastReceiver mbr = new MinuteBroadcastReceiver (); //广播接收器变量，并实例化

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        msgPanel =(TextView)findViewById(R.id.msgPanel);
    }
    @Override
    protected void onStart() {
        super.onStart();
        IntentFilter filter = new IntentFilter(Intent.ACTION_TIME_TICK);
        registerReceiver(mbr, filter);  // mbr为接收器对象
    }
    @Override
    protected void onStop() {
        super.onStop();
        unregisterReceiver(mbr);  // mbr为接收器对象
    }
    class MinuteBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            // 格式化当前时间
            SimpleDateFormat dfm = new SimpleDateFormat("HH:mm:ss");
            String msg = String.format("%s 收到一个整分钟广播！", dfm.format(new Date()));
            //msgPanel为页面中消息标签组件；
            msgPanel.setText(msgPanel.getText().toString()+"\n"+msg);
        }
    }
}